<template>
  <j-modal
    :confirmLoading="confirmLoading"
    :dialogStyle="dialogStyle"
    :title="title"
    :visible="visible"
    :width="1200"
    cancelText="关闭"
    switchFullscreen
    @cancel="handleCancel"
    @ok="handleOk">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row>
          <a-col :offset="2" :sm="9" :xs="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="现状年份">
              <a-checkbox-group :options="plainOptionsCurrent" :default-value="model.year" @change="onChange($event, 0)"
                                v-decorator="['year', {rules: [{required: true,message: '现状年份必须要选择!',}]}]" />
              <br />
              <a-button @click="handleYearInput(0)">{{ showInput ? '取消' : '新增年份' }}</a-button>
              <a-input-search v-model="inputYear" placeholder="请输入年份" @search="addYear($event,0)" class="addInput"
                              v-if="showInput">
                <a-button slot="enterButton" type="primary">
                  <a-icon type="plus" />
                </a-button>
              </a-input-search>
              <a-alert
                v-if="showAlert.year"
                :message="alert.year"
                type="error"
                show-icon
                style="margin-top: 10px;"
              />
            </a-form-item>
          </a-col>
          <a-col :offset="2" :sm="9" :xs="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="目标年份">
              <a-checkbox-group :options="plainOptionsTarget" :default-value="model.year1" @change="onChange($event, 1)"
                                v-decorator="['year1', {rules: [{required: true,message: '目标年份必须要选择!',}]}]" />
              <br />
              <a-button @click="handleYearInput(1)">{{ showInputYear1 ? '取消' : '新增年份' }}</a-button>
              <a-input-search v-model="inputYear1" placeholder="请输入年份" @search="addYear($event,1)" class="addInput"
                              v-if="showInputYear1">
                <a-button slot="enterButton" type="primary">
                  <a-icon type="plus" />
                </a-button>
              </a-input-search>
              <a-alert
                v-if="showAlert.year1"
                :message="alert.year1"
                type="error"
                show-icon
                style="margin-top: 10px;"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :offset="2" :sm="9" :xs="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="指标">
              <a-input v-decorator="['indexStr', {
            rules: [
              {
                required: true,
                message: '指标不能为空!',
              },
            ],
            }]" placeholder="请输入指标名称" />
            </a-form-item>
          </a-col>
          <a-col :offset="2" :sm="9" :xs="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="单位">
              <a-input v-decorator="['unit', {
            rules: [
              {
                required: true,
                message: '单位不能为空!',
              },
            ],
            }]" placeholder="请输入单位" />
            </a-form-item>
          </a-col>
        </a-row>

        <!--        <div class="currentYear">现状年份数据</div>-->
        <a-divider style="margin-bottom: 20px;font-size: 18px;" v-if="model.year && model.year.length>0">现状年份数据
        </a-divider>
        <a-row>
          <a-col v-for="(item,index) in model.year" :key="index" :offset="2" :sm="9" :xs="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :label="item">
              <a-input v-decorator="[`${item}`, {
            rules: [
              {
                required: true,
                message: '年份数据不能为空!',
              },
            ],
            }]" placeholder="请输入单位" />
            </a-form-item>
          </a-col>
        </a-row>

        <!--        <div class="currentYear">目标年份数据</div>-->
        <a-divider style="margin-bottom: 20px;font-size: 18px;" v-if="model.year1 && model.year1.length>0">
          目标年份数据
        </a-divider>
        <a-row>
          <a-col v-for="(item,index) in model.year1" :key="index" :offset="2" :sm="9" :xs="12">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :label="item">
              <a-input v-decorator="[`${item}`, {
            rules: [
              {
                required: true,
                message: '单位不能为空!',
              },
            ],
            }]" placeholder="请输入单位" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
import pick from 'lodash.pick'
import moment from 'moment'
import { httpAction, postAction } from '@api/manage'

export default {
  name: 'standardModal',
  data() {
    return {
      current: {},
      model: {},
      alert: {
        year: '',
        year1: '',
        yearPass: false,
        year1Pass: false
      },
      showAlert: {
        year: false,
        year1: false
      },
      inputYear: '',
      inputYear1: '',
      showInput: false,
      showInputYear1: false,
      plainOptionsCurrent: [],
      plainOptionsTarget: [],
      confirmLoading: false,
      title: '',
      visible: false,
      form: this.$form.createForm(this),
      currentTime: '',
      dialogStyle: {
        top: '300px'
        // right:"20px",
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      validatorRules: {
        totalEnergyConsumption: {
          rules: [{ required: true, trigger: 'change', message: '请输入数字！', pattern: '^\d{1,}\.\d{1,}|\d{1,}]/g' }]
        }
      },
      url: {
        add: '/carbon/targetTrackeList/add',
        edit: '/carbon/targetTrackeList/edit'
      }
    }
  },
  created() {
    this.getCurrentData()
  },
  watch: {
    //   监听inputYear的变化
    inputYear(val) {
      //   验证正则
      let reg = /^(?:[2-9]\d{3}|[3-9]\d{3})$/
      if (val && !reg.test(val)) {
        // 如果有值且未通过正则验证
        this.showAlert.year = true // 显示提示
        this.alert.year = '请输入4位且大于2000的数字'
      } else if (val && reg.test(val)) {
        // 如果有值且通过正则验证
        this.alert.yearPass = true // 通过验证
        this.showAlert.year = false // 隐藏提示
      } else {
        this.showAlert.year = false // 隐藏提示
        this.alert.yearPass = false // 重置是否通过验证
      }
    },
    inputYear1(val) {
      //   验证正则
      let reg = /^(?:[2-9]\d{3}|[3-9]\d{3})$/
      if (val && !reg.test(val)) {
        this.showAlert.year1 = true
        this.alert.year1 = '请输入4位且大于2000的数字'
      } else if (val && reg.test(val)) {
        // 如果有值且通过正则验证
        this.alert.year1Pass = true // 通过验证
        this.showAlert.year1 = false // 隐藏提示
      } else {
        this.showAlert.year1 = false // 隐藏提示
        this.alert.year1Pass = false // 重置是否通过验证
      }
    }
  },
  mounted() {
    if (localStorage.getItem('currentYearList')) {
      this.plainOptionsCurrent = JSON.parse(localStorage.getItem('currentYearList'))
      this.plainOptionsCurrent.sort((a, b) => {
        return a - b
      })
    }
    if (localStorage.getItem('targetList')) {
      this.plainOptionsTarget = JSON.parse(localStorage.getItem('targetList'))
      this.plainOptionsTarget.sort((a, b) => {
        return a - b
      })
    }

  },
  methods: {
    onChange(checkedValues, type) {
      if (type === 0) {
        this.model.year = checkedValues
      } else {
        this.model.year1 = checkedValues
      }
    },
    handleYearInput(type) {
      if (type === 0) {
        this.showInput = !this.showInput
      } else {
        this.showInputYear1 = !this.showInputYear1
      }
    },
    addYear(value, type) {
      if (type == 0 && this.alert.yearPass) {
        this.plainOptionsCurrent.push(value)
        // 获取表单中year的值
        let selectedYear = this.form.getFieldValue('year')
        selectedYear.push(value)
        this.form.setFieldsValue({ year: selectedYear })
        //   数组重新排序
        this.plainOptionsCurrent.sort((a, b) => {
          return a - b
        })
        this.inputYear = '' // 重置输入值

      } else if (type == 1 && this.alert.year1Pass) {
        this.plainOptionsTarget.push(value)
        let selectedYear = this.form.getFieldValue('year1')
        selectedYear.push(value)
        this.form.setFieldsValue({ year1: selectedYear })
        //   数组重新排序
        this.plainOptionsTarget.sort((a, b) => {
          return a - b
        })
        this.inputYear1 = '' // 重置输入值
      }

    },
    getCurrentData() {
      if (this.currentTime === '') {
        this.currentTime = moment().format('YYYY-MM-DD')
      }
    },
    add() {
      this.edit({})
    },
    edit(record) {
      console.log(record)
      this.visible = true
      this.form.resetFields()
      if (Object.keys(record).length > 0) {
        this.model = Object.assign({}, record)
        this.model.year = this.model.year ? this.model.year.split(',') : []
        this.model.year1 = this.model.year1 ? this.model.year1.split(',') : []
        let yearData = JSON.parse(record.target)
        console.log(yearData)
        this.model = Object.assign(this.model, yearData)
        console.log(this.model)
      }
      this.$nextTick(() => {
        this.form.setFieldsValue((
          this.model
        ))
      })
    },
    handleChange(value) {
      console.log(value)
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
    handleOk() {
      let that = this
      this.form.validateFields((err, values) => {
        if (!err) {
          let httpurl = ''
          let method = ''
          this.confirmLoading = true
          console.log(this.model)
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'post'
          }
          console.log(httpurl)
          let current = {}
          let target = {}
          current = values.year.reduce((item, year) => {
            console.log(values[year])
            item[year] = values[year]
            return item
          }, {})
          target = values.year1.reduce((item, year) => {
            console.log(values[year])
            item[year] = values[year]
            return item
          }, {})

          // 组合两个对象current和target
          let yearData = Object.assign(current, target)
          // 转为字符串
          let yearDataStr = JSON.stringify(yearData)
          console.log(yearDataStr)

          values.target = yearDataStr
          values.year = values.year.join(',')
          values.year1 = values.year1.join(',')
          values.id = this.model.id

          let formData = Object.assign({}, values)
          console.log(formData)
          httpAction(httpurl, formData, method).then(res => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('refresh')
            } else {
              that.$message.error(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
            that.$parent.$parent.loadData()
          })
        }
      })
    }
  }
}
</script>

<style scoped>
.currentYear {
  font-size: 20px;
  margin: 10px 0 30px;
  text-align: center;
}

.addInput {
  margin-left: 20px;
  width: 60%
}
</style>